package com.haynes.meetxiaohai.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 * ControllerAdvice：对所有Controller进行拦截
 * @author Haynes
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());
//        1.判断异常信息中是否包含Duplicate entry
        if (exception.getMessage().contains("Duplicate entry")){
//            2.把异常信息根据空格进行分割：Duplicate entry 'zhangsan' for key 'employee.idx_username'
            String[] split = exception.getMessage().split(" ");
//            3.拿到下标为2的值：'zhangsan'
            String msg= split[2]+"已存在";
//            4.输出
            return R.error(msg);
        }
        return R.error("未知异常！");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        log.error(exception.getMessage());

        return R.error(exception.getMessage());
    }
}
